/*
 PureMVC AS3 Demo - Flex CafeTownsend
 Copyright (c) 2007-08 Michael Ramirez <michael.ramirez@puremvc.org>
 Parts Copyright (c) 2005-07 Adobe Systems, Inc. 
 Your reuse is governed by the Creative Commons Attribution 3.0 License
 */
package vn.demand.dragon.view
{
	import flash.events.Event;
	
	import flexed.widgets.alerts.alert;
	
	import mx.collections.XMLListCollection;
	import mx.controls.Alert;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.events.CloseEvent;
	
	import org.puremvc.as3.interfaces.*;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import vn.demand.dragon.CommonCommand;
	import vn.demand.dragon.MarketingApplicationFacade;
	import vn.demand.dragon.model.CompanyProxy;
	import vn.demand.dragon.model.MasterdataProxy;
	import vn.demand.dragon.model.vo.Company;
	import vn.demand.dragon.view.components.CustomerList;
    
    /**
     * A Mediator for interacting with the EmployeeList component
     */
    public class CustomerListMediator extends Mediator implements IMediator
    {
        // Cannonical name of the Mediator
        public static const NAME:String = "CustomerListMediator";
        
        public var id:String = null;
        
        /**
         * Constructor. 
         */
        public function CustomerListMediator(viewComponent:Object ) 
        {
            // pass the viewComponent to the superclass where 
            // it will be stored in the inherited viewComponent property
            super( NAME, viewComponent );
			
			customerProxy = CompanyProxy( facade.retrieveProxy( CompanyProxy.NAME ) );
			masterdataProxy = MasterdataProxy( facade.retrieveProxy( MasterdataProxy.NAME ) );
			
			customerList.addEventListener(CustomerList.SELECT_CUSTOMER, selectCustomer);
			customerList.addEventListener(CustomerList.NEW_CUSTOMER, newCustomer);
			customerList.addEventListener(CustomerList.DELETE_CUSTOMER, deleteCustomer);
			customerList.addEventListener(CustomerList.CLOSE_CUSTOMERS_LIST, closeCustomerList);
			customerList.addEventListener(CustomerList.REFRESH_CUSTOMERS_LIST, onRefreshCustomerList);
			
//			customerList.dgCustomer.columns[2].labelFunction = lfQuotationStatus; 
			
        }

		public function newCustomer(event:Event):void {
			sendNotification(CommonCommand.ADD_CUSTOMER, null);
		}
		
		public function deleteCustomer(event:Event):void {
			var com:Company = new Company(customerList.dgCustomer.selectedItem);
			if (com != null) {
				alert.confirm("Do you want to remove [" + com.company_name + "]?", function(e:CloseEvent) {
    			if (e.detail == Alert.NO) {
        			return;
        		}
        		sendNotification(CommonCommand.DELETE_CUSTOMER, com);
        		});
			} else {
				alert.info("Select the customer to delete");
			}
		}
		
		public function onRefreshCustomerList(event:Event):void {
			doRefreshCustomerList();
		}
		
		public function doRefreshCustomerList():void {
			customerProxy.loadCustomers();
		}

		public function selectCustomer(event:Event):void {
			if (customerList.dgCustomer.selectedIndex < 0) {
				alert.error("You should select a customer");
				return;
			}
			var company = new Company(customerList.dgCustomer.selectedItem);
			sendNotification(CommonCommand.CUSTOMERS_SELECTED, company);
		}
		
		public function closeCustomerList(event:Event):void {
			sendNotification(CommonCommand.CLOSE_CUSTOMERS_LIST, customerList);
		}

        /**
         * List all notifications this Mediator is interested in.
         * <P>
         * Automatically called by the framework when the mediator
         * is registered with the view.</P>
         * 
         * @return Array the list of Nofitication names
         */
        override public function listNotificationInterests():Array 
        {
            return [ CommonCommand.LOAD_CUSTOMERS_SUCCESSFUL,
            		 CommonCommand.CUSTOMERS_UPDATED_SUCESSFUL,
            		 CommonCommand.CUSTOMERS_UPDATE_FAILED, 
            		 CommonCommand.DELETE_CUSTOMER,
            		 CommonCommand.DELETE_CUSTOMER_SUCCESSFUL,
            		 CommonCommand.DELETE_CUSTOMER_FAILED];
        }

        /**
         * Handle all notifications this Mediator is interested in.
         * <P>
         * Called by the framework when a notification is sent that
         * this mediator expressed an interest in when registered
         * (see <code>listNotificationInterests</code>.</P>
         * 
         * @param INotification a notification 
         */
        override public function handleNotification( note:INotification ):void 
        {
            switch ( note.getName() ) 
			{
                case CommonCommand.LOAD_CUSTOMERS_SUCCESSFUL:
                    customerList.dgCustomer.dataProvider = note.getBody() as XMLListCollection;
                    break;
				case CommonCommand.LOAD_CUSTOMERS_FAILED:
					customerList.dgCustomer.errorString = customerProxy.errorStatus;
					break;
				case MarketingApplicationFacade.BROWSE_QUOTATION_LIST:
					break;
				case CommonCommand.CUSTOMERS_UPDATED_SUCESSFUL:
					customerProxy.loadCustomers();
					break;
				case CommonCommand.CUSTOMERS_UPDATE_FAILED:
					alert.error(note.getBody() as String);
					break;	
				case CommonCommand.DELETE_CUSTOMER_SUCCESSFUL:
					customerProxy.loadCustomers();
//					var customer:Object = note.getBody();
//					alert.info("Customer " + customer.company_name + " deleted");
					break;
				case CommonCommand.DELETE_CUSTOMER_FAILED:
					alert.error(note.getBody() as String);
					break;	
			    case CommonCommand.DELETE_CUSTOMER:
			   		 var company = new Company(customerList.dgCustomer.selectedItem);
			        customerProxy.remove(company);
			        break;
            }
        }
                    
        /**
         * Cast the viewComponent to its actual type.
         * 
         * <P>
         * This is a useful idiom for mediators. The
         * PureMVC Mediator class defines a viewComponent
         * property of type Object. </P>
         * 
         * <P>
         * Here, we cast the generic viewComponent to 
         * its actual type in a protected mode. This 
         * retains encapsulation, while allowing the instance
         * (and subclassed instance) access to a 
         * strongly typed reference with a meaningful
         * name.</P>
         * 
         * @return EmployeeList the viewComponent cast to EmployeeList
         */
        protected function get customerList():CustomerList
		{
            return viewComponent as CustomerList;
        }
		
//		private function logout( event:Event = null ):void
//		{
//			sendNotification( ApplicationFacade.APP_LOGOUT );
//		}
//		
//		private function addEmployee( event:Event = null ):void
//		{
//			sendNotification( ApplicationFacade.ADD_EMPLOYEE );
//		}
//		
//		private function updateEmployee( event:Event = null ):void
//		{
//			sendNotification( ApplicationFacade.UPDATE_EMPLOYEE, quotationList.employees_li.selectedItem);
//		}
		
		public function lfQuotationStatus(item:Object, column:DataGridColumn):String {
        	return masterdataProxy.getQuotationStatusById(item[column.dataField]);
        }
		
		private var customerProxy:CompanyProxy;
		private var masterdataProxy:MasterdataProxy;
    }
}